package org.example.utils;

import cn.hutool.core.io.FileUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author liuyunzhe
 * @version 1.0
 * @description: TODO
 * @date 2023/5/17 9:31
 */
@AllArgsConstructor
public class ByteArrayMultipartFile implements MultipartFile, Serializable {

    private static final long serialVersionUID = -838255113442389980L;

    private String fileName;

    private byte[] bytes;

    private String originalFileName;

    private String contentType;


    @Override
    public String getName() {
        return fileName;
    }

    @Override
    public String getOriginalFilename() {
        return originalFileName;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return ArrayUtils.isEmpty(bytes);
    }

    @Override
    public long getSize() {
        return bytes == null ? 0 : bytes.length;
    }

    @Override
    public byte[] getBytes() throws IOException {
        return bytes;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        return in;
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        FileUtil.writeBytes(bytes, dest);
    }
}
